<?php

// ------------------------------------------------------------------------
// |@Author       : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Date         : 2025-05-11 01:38:19
// |@----------------------------------------------------------------------
// |@LastEditTime : 2025-05-11 02:38:02
// |@----------------------------------------------------------------------
// |@LastEditors  : Jarmin <topextend@qq.com>
// |@----------------------------------------------------------------------
// |@Description  : 接口版本服务
// |@----------------------------------------------------------------------
// |@FilePath     : ApiVersionService.php
// |@----------------------------------------------------------------------
// |@Copyright (c) 2025 http://www.ladmin.cn All Rights Reserved.
// ------------------------------------------------------------------------
declare (strict_types=1);

namespace think\admin\service;

use think\admin\Service;
use think\admin\repository\ApiVersionRepository;

/**
 * 接口版本服务
 * Class ApiVersionService
 * @package app\common\service
 */
class ApiVersionService extends Service
{
    /**
     * 服务初始化
     * @return void
     */
    protected function initialize(): void
    {
        $this->repository = new ApiVersionRepository($this->app);
    }

    /**
     * 从缓存获取接口信息
     * @param string $path
     * @param string $method
     * @return array|null
     */
    public function getInterfaceInfo($path, $method): ?array
    {
        return $this->repository->getInterfaceInfo($path, $method);
    }

    /**
     * 获取版本信息
     * @param string $version
     * @return array|null
     */
    public function getVersionInfo($version): ?array
    {
        return $this->repository->getVersionInfo($version);
    }

    /**
     * 检查灰度发布
     * @param string $version
     * @param Request $request
     * @return string|null
     */
    public function checkGrayRelease($version, $request): ?string
    {
        $grayRelease = $this->repository->getGrayReleaseInfo($version);
        if (!$grayRelease) {
            return null;
        }

        // 检查白名单
        if ($grayRelease['white_list']) {
            $userId = $request->header('User-Id');
            if ($userId && in_array($userId, $grayRelease['white_list'])) {
                return $grayRelease['version'];
            }
        }

        // 检查灰度百分比
        if ($grayRelease['gray_percent'] > 0) {
            $hash = crc32($request->ip() . $request->header('User-Agent'));
            if ($hash % 100 < $grayRelease['gray_percent']) {
                return $grayRelease['version'];
            }
        }

        return $grayRelease['fallback_version'];
    }
}
